package com.ruoyi.common;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * 算法工具
 */
public class AES128Util {

    private final static String HEX_KEY = "D96BBF259EACCAEF69FCE916C3738618";
    public final static String ENCODING = "UTF-8";

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 生成密钥
     * 自动生成16进制 编码后的AES128位密钥
     *
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String getAESKey() throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128);//要生成多少位，只需要修改这里即可128, 192或256
        SecretKey sk = kg.generateKey();
        byte[] b = sk.getEncoded();
        return parseByte2HexStr(b);
    }

    /**
     * AES 加密
     * @param text      待加密的字符串
     * @return 加密后的byte[] 数组
     * @throws Exception
     */
    public static String getAESEncodeHex(String text){
        try {
            byte[] key = parseHexStr2Byte(HEX_KEY);
            SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
            byte[] encoded = cipher.doFinal(text.getBytes(ENCODING));
            String encodedHex = parseByte2HexStr(encoded);
            //System.out.println("encodedBase64:" + encodedBase64);
            return encodedHex;
        }catch (Exception ex){
            return null;
        }

    }

    /**
     * AES解密
     * @param hexText      待解密的字符串
     * @return 解密后的byte[] 数组
     * @throws Exception
     */
    public static String getAESDecode(String hexText) throws Exception {
        byte[] encodedByte = parseHexStr2Byte(hexText);
        byte[] key = parseHexStr2Byte(HEX_KEY);
        SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
        byte[] decoded = cipher.doFinal(encodedByte);
        String decodedTxt = new String(decoded, "UTF-8");
        return decodedTxt;
    }

//    public static void main(String[] args) {
//        try {
//            String aex = getAESKey();
//            System.out.println(aex);
//            String hexKey = "D96BBF259EACCAEF69FCE916C3738618";//"getAESKey();"
//
//            System.out.println("16进制秘钥：" + hexKey);
//            //  byte[] encoded = getAESEncode(hexKey, "10001");
//            String encodedHex = getAESEncodeHex(hexKey, "10001");
//            System.out.println("encodedHex:" + encodedHex);
//
//            // 注意，这里的encoded是不能强转成string类型字符串的
//           // byte[] encodedByte = parseHexStr2Byte(encodedHex);
//           // byte[] decoded = getAESDecode(hexKey, encodedHex);
//            System.out.println(getAESDecode(hexKey,encodedHex));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
